import 'dart:async';

import 'package:bigegg/global/xmm_storage_manager.dart';
import 'package:bigegg/utils/file/xmm_file_util.dart';
import 'package:bigegg/utils/xmm_toast_util.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';

import 'xmm_audio_session.dart';

class XmmAudioRecorder {
  FlutterSoundRecorder? _recorderModule;

  int _maxLength = 60;

  Duration? duration;

  Function(String path, int duration)? finished;

  XmmAudioRecorder({this.finished});

  void setMaxLength(int max) {
    _maxLength = max;
  }

  void setFinishCallback(Function(String path, int duration) finished) {
    this.finished = finished;
  }

  Future<bool> getPermissionStatus() async {
    Permission permission = Permission.microphone;
    //granted 通过，denied 被拒绝，permanentlyDenied 拒绝且不在提示
    PermissionStatus status = await permission.status;
    if (status.isGranted) {
      return true;
    } else if (status.isDenied) {
      requestPermission(permission);
    } else if (status.isPermanentlyDenied) {
      openAppSettings();
    } else if (status.isRestricted) {
      requestPermission(permission);
    } else {}
    return false;
  }

  ///申请权限
  void requestPermission(Permission permission) async {
    PermissionStatus status = await permission.request();
    if (status.isPermanentlyDenied) {
      openAppSettings();
    }
  }

  init() async {
    _recorderModule = FlutterSoundRecorder();
    _recorderModule?.openRecorder();
    _recorderModule?.setSubscriptionDuration(const Duration(milliseconds: 100));
    _recorderModule?.onProgress?.listen((e) {
      duration = e.duration;
      var date = DateTime.fromMillisecondsSinceEpoch(
        e.duration.inMilliseconds,
        isUtc: true,
      );
      //设置了最大录音时长
      if (date.second >= _maxLength) {
        stopRecorder();
        return;
      }
    });
    XmmAudioSession.instance.initSession();
  }

  /// 开始录音
  startRecorder() async {
    try {
      //获取麦克风权限
      var isGranted = await getPermissionStatus();
      if (!isGranted) {
        return;
      }
      if (_recorderModule == null) {
        await init();
      }
      //用户允许使用麦克风之后开始录音
      String dir = XmmStorageManager.temporaryDirectory?.path ?? "";
      var time = DateTime.now().millisecondsSinceEpoch;
      String path = '$dir/$time${ext[Codec.aacADTS.index]}';

      //这里我录制的是aac格式的，还有其他格式
      await _recorderModule?.startRecorder(
        toFile: path,
        codec: Codec.aacADTS,
        bitRate: 8000,
        numChannels: 1,
        sampleRate: 8000,
      );
    } catch (err) {
      cancelRecord();
    }
  }

  ///结束录音
  stopRecorder() async {
    try {
      String? path = await _recorderModule?.stopRecorder();
      if (path == null) {
        XmmToastUtils.show("record failed");
        return;
      }
      if (!await XmmFileUtil.isFileExists(path)) {
        XmmToastUtils.show("record failed");
        return;
      }
      if (duration == null || (duration?.inSeconds ?? 0) < 1) {
        XmmToastUtils.show('recording can\'t be less than 1 second');
        return;
      }
      finished?.call(path, duration?.inSeconds ?? 0);
      duration = null;
    } catch (err) {
      err.printError;
    }
  }

  ///取消录音
  cancelRecord() async {
    try {
      String? path = await _recorderModule?.stopRecorder();
      if(path != null){
        XmmFileUtil.deleteFile(path);
      }
    } catch (err) {
      err.printError;
    }
  }

  ///销毁录音
  void dispose() {
    _release();
  }

  /// 释放录音
  Future<void> _release() async {
    try {
      await _recorderModule?.closeRecorder();
    } catch (e) {
      e.printError;
    }
  }
}
